package geo.model.config
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import geo.model.events.GeoModelEvent;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	[Event(name="configured", type="geo.model.events.GeoModelEvent")]
	
	[Event(name="config_default", type="geo.model.events.GeoModelEvent")]
	
	public class Configurer extends EventDispatcher
	{
		public function Configurer(target:IEventDispatcher=null)
		{
			super(target);
			loadConfig();
		}
		
		//public var config:Config = new Config();
		
		private function loadConfig():void {
			var configService:HTTPService = new HTTPService();
			configService.url = "geo/model/config/configuration.xml";
			configService.useProxy = false;
			configService.resultFormat = HTTPService.RESULT_FORMAT_E4X;
			configService.addEventListener(ResultEvent.RESULT, resultHandler);
			configService.addEventListener(FaultEvent.FAULT, faultHandler);
			trace("requesting configuration...");
			configService.send();
		}
		
		/**
		 * On retrieving a successfult request/response, load the configuration xml elements into the Config object.
		 * Any problems with the configuration xml parsing will throw an error that is caught and the defaults are loaded.
		 */
		private function resultHandler(event:ResultEvent):void {
			trace("successful result, parsing result...");
			var configXML:XML = event.result as XML;
			//var config = new Config();
			try {
				Config.HOST = configXML..host;
				Config.PORT = configXML..port;
				Config.WPS_PATH = configXML..path;
				Config.MAX_RESULTS = configXML..max;
				trace(Config.HOST);
				trace(Config.PORT);
				trace(Config.WPS_PATH);
				trace(Config.MAX_RESULTS);
				dispatchEvent(new GeoModelEvent(GeoModelEvent.CONFIGURED));
			}
			catch (e:Error) {
				trace(e.message);
				loadDefaults();
			}

			
		}
		
		/**
		 * On failure of the request/response of the configuration.xml, load some default information into the Config object.
		 */
		private function faultHandler(event:FaultEvent):void {
			trace("fault:" + event.fault.faultString);
			trace("loading default configuration");
			loadDefaults();
		}
		
		private function loadDefaults():void {
			Config.HOST = "localhost";
			Config.PORT = "8080";
			Config.WPS_PATH = "geoserver/wps";
			Config.MAX_RESULTS = "10000";
			trace(Config.HOST);
			trace(Config.PORT);
			trace(Config.WPS_PATH);
			trace(Config.MAX_RESULTS);
			dispatchEvent(new GeoModelEvent(GeoModelEvent.CONFIG_DEFAULT));
		}
	}
}